<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/13
 * Time: 9:36
 */

namespace App\Console\Commands;

use App\Model\Members;
use App\Model\Shareholders;
use App\Model\ShopOrder;
use App\Model\Poundage;
use App\Model\RecordBonus;
use App\Model\RecordTransaction;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Command;
class CalculateConsole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calculates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '股东分红';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 股东分润计算
     */
    public function handle()
    {
        //判断是否重复
        $ShareholdersModer = new Shareholders();
        $Shareholders = $ShareholdersModer->where('time','>',time()-86300)->where('time','<',time())->first();
        if ($Shareholders) {
            exit('失败');
        }
        //会员列表
        $MemberModer = new Members();
        $members = $MemberModer->where(['shareholder'=>1])->select(['credit1','credit2','credit3','credit4','uid'])->get();
        //订单列表
        $OrderModer = new ShopOrder();
        $price = $OrderModer->whereIn('ordertype' ,[2,3])->where('status' ,'>=' ,1)->where('paytime','>',1542297600)->where('paytime','<',1542383999)->sum('price');
        //系统设置
        $PoundageModer = new  Poundage();
        $Poundage = $PoundageModer->first();
        //计算金额
        $recommend = RETAIN_TWO($price * ($Poundage['equity'] * 0.01));
        $money = RETAIN_TWO($recommend / count($members));
        $ordersn = ORDER_SN();
        $uid = '';
        DB::beginTransaction(); //开启事务
        foreach ($members as $k => $v) {
            $uid = empty($uid)?$v['uid']:$uid.','.$v['uid'];
            //扣除平台费和复投币
            $recommendMoney = CALCULATE($Poundage, $money);
            $v['credit2'] += $recommendMoney['money'];
            $v['credit3'] += $recommendMoney['redelivery'];
            //添加记录
            $this->addOrder($v['uid'], $money, 5, '股东分红', $recommendMoney, 0,$ordersn);
            //更新会员数据
            $rico = $MemberModer->where(['uid' => $v['uid']])->update($v['attributes']);
            if(empty($rico)){
                DB::rollback();  //回滚
            }
        }
        //添加股东分红记录
        $Shareholders = new Shareholders();
        $data = [
            'uid' => $uid,
            'total' => $price,
            'people' => count($members),
            'money' => $money,
            'ordersn' => $ordersn,
            'time' => time(),
        ];
        $rico = $Shareholders->insert($data);
        if($rico){
            DB::commit();  //提交
        }
    }
    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null , $money = null , $type = null ,$explain = '', $manageMoney = array(),$company_id = null,$ordersn = '')
    {
        $ordersn = empty($ordersn)?ORDER_SN():$ordersn;
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid'       => $uid,
            'ordersn'   => $ordersn,
            'money'     => $money,
            'type'      => $type,
            'time'      => time(),
            'explain'   => $explain,
            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain.'：'.$manageMoney['money'].'，复投费：'.$manageMoney['redelivery'].'，平台费：'. $manageMoney['platform_fee'],
            'time' => 1542383999,
            'company_id' => $company_id,
        ];
        $RecordBonus->add_bonus($bonusData);
    }
}